﻿using System;
using System.Windows.Controls;
using System.Windows.Markup;
using System.Windows.Media.Imaging;

namespace Foundation
{
    /// <summary>
    /// XAML extension for picturies.
    /// </summary>
    public class Picture : MarkupExtension
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="Picture"/> class.
        /// </summary>
        public Picture()
        {
            Width = -1;
            Height = -1;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="Picture"/> class.
        /// </summary>
        /// <param name="path">The path.</param>
        public Picture(string path)
        {
            Path = path;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="Picture"/> class.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <param name="size">The size.</param>
        public Picture(string path, int size)
        {
            Path = path;
            Width = Height = size;
        }

        /// <summary>
        /// Gets or sets the path.
        /// </summary>
        /// <value>
        /// The path.
        /// </value>
        public string Path { get; set; }

        /// <summary>
        /// Gets or sets the width.
        /// </summary>
        /// <value>
        /// The width.
        /// </value>
        public double Width { get; set; }

        /// <summary>
        /// Gets or sets the height.
        /// </summary>
        /// <value>
        /// The height.
        /// </value>
        public double Height { get; set; }

        /// <summary>
        /// When implemented in a derived class, returns an object that is set as the value of the target property for this markup extension.
        /// </summary>
        /// <param name="serviceProvider">Object that can provide services for the markup extension.</param>
        /// <returns>
        /// The object value to set on the property where the extension is applied.
        /// </returns>
        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            try
            {
                var uri = new Uri("pack://application:,,/" + Path);
                var image = new BitmapImage(uri);

                if (Height < 0)
                {
                    Height = image.Height;
                }

                if (Width < 0)
                {
                    Height = image.Width;
                }

                return new Image {Source = image, Width = Width, Height = Height};
            }
            catch (Exception)
            {
                return null;
            }
        }
    }
}
